<template>
  <view class="viewport">
    <view class="header" :style="{ paddingTop: safeAreaInsets!.top + 'px' }">
      <view class="left icon-left" @tap="Onleft()"></view>
      <uni-title type="h1" align="center" title="资产详情" class="text"></uni-title>
      <view class="right icon-sort" @tap="orderby()"></view>
    </view>
    <scroll-view enable-back-to-top scroll-y class="scroll">
      <view class="count">
        <view class="space_between">
          <!-- <text>{{ getAccountResponse?.AccountCard }}</text> -->
          <picker
            @change="pickerAccountTypeChange"
            mode="selector"
            :range="accountTypeNames"
            range-key="AccountCard1AccountTypeName"
          >
            <text class="account">{{
              curAccountTypeName.AccountCard1AccountTypeName
            }}</text></picker
          >

          <text @tap="OnDropDialog">注销</text>
        </view>
        <h5 class="txt">{{ AccountCard == '股票' ? '本金(收益)' : '账户余额' }}</h5>
        <text class="amount" @tap="OpenPwdDialog">{{ maskedAmount }}</text>
        <view class="bottom">
          <text @tap="OpenSarchDialog">编辑</text>
          <text @tap="add">记一笔</text>
        </view>
      </view>
      <view class="condition">
        <view>
          <view class="time">
            <picker
              @change="pickerYearChange"
              mode="selector"
              :range="yearData"
              :value="selectYearIndex"
            >
              <text class="account">{{ curYear }}</text></picker
            >
            <text class="tip">-</text>
            <picker
              @change="pickerMonthChange"
              mode="selector"
              :range="monthData"
              :value="selectMonthIndex"
            >
              <text class="account">{{ curMonth }}</text></picker
            >
            <text class="tip">收入：{{ data == null ? 0 : data[0]?.ShouruAmount }}</text>
            <text class="tip">支出：{{ data == null ? 0 : data[0]?.ZhichuAmount }}</text>
            <text class="tip"
              >结余：{{
                data == null ? 0 : Math.round(data[0]?.ShouruAmount + data[0]?.ZhichuAmount)
              }}</text
            >
          </view>
        </view>
      </view>
      <!-- 具体明细 -->
      <view class="scroll">
        <view class="content">
          <view class="detail" v-for="dataCount in data" :key="dataCount.MonthDay">
            <view class="tip">
              <view>{{ dataCount.MonthDay }} {{ dataCount.Week }}</view>
              <view>收支:{{ dataCount.TotalAmount }}</view>
            </view>
            <view class="content" v-for="data in dataCount.Data" :key="data.ID">
              <view class="name" @tap="openPopup(data.ID)">
                <view
                  v-if="data?.GoodsIcon.startsWith('icon')"
                  class="circle"
                  :class="data?.GoodsIcon"
                ></view>
                <view v-else class="circle bold">{{ data?.GoodsIcon }}</view>
                <view>（{{ data.Amount }}）{{ data.Goods }}</view>
                <view class="userName">{{ data.UserName }}</view>
                <view class="userName">{{ data.AccountTypeName }}</view>
              </view>
              <view>{{ data.Amount }}</view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    <!-- 编辑 弹窗 -->
    <uni-popup
      ref="searchDialog"
      borderRadius="20rpx"
      background-color="#fafafa"
      @close="searchDialog?.close()"
    >
      <view class="popup-content popup searchPup">
        <view class="pheader">
          <text class="btn ok" @tap="SubmitSarchDialog()">确 认</text>
          <text class="btn del" @tap="CloseSarchDialog()">取 消</text>
        </view>
        <view class="content">
          <uni-forms ref="baseForm" :modelValue="form">
            <uni-forms-item label="账户类型" label-width="170rpx">
              <uni-easyinput type="text" v-model="AccountTypeName" />
            </uni-forms-item>
            <uni-forms-item label="账户名称" label-width="170rpx">
              <uni-easyinput type="text" v-model="AccountCard" />
            </uni-forms-item>
            <uni-forms-item label="账户图标" label-width="170rpx">
              <uni-data-select v-model="iconPath" :localdata="iconPathData"></uni-data-select>
            </uni-forms-item>
            <uni-forms-item label="金额" label-width="170rpx">
              <uni-easyinput type="number" v-model="amount" />
            </uni-forms-item>
          </uni-forms>
        </view>
      </view>
    </uni-popup>
  </view>
  <!-- 密码 弹窗 -->
  <uni-popup
    ref="popup"
    type="center"
    borderRadius="20rpx"
    background-color="#fafafa"
    @close="popup?.close()"
  >
    <view class="popup-content popup">
      <view class="pheader">
        <text class="title">请输入密码</text>
        <text class="btn del" @tap="ComfirmPwd()">确 认</text>
      </view>
      <view class="content">
        <view class="Good">
          <view>
            <input class="uni-input" v-model="pwd" password placeholder="请输入查看密码" />
          </view>
        </view>
      </view>
    </view>
  </uni-popup>

  <!-- 商品详情 弹窗 -->
  <uni-popup
    ref="popupDetail"
    type="bottom"
    borderRadius="20rpx"
    background-color="#fafafa"
    @close="popupDetail?.close()"
  >
    <view class="popup-content popupDetail">
      <view class="pheader">
        <text class="title">账单详情</text>
        <text class="btn ok" @tap="OnUpdateGoodDetail()">修 改</text>
        <text class="btn del" @tap="OnAlertDialog()">删 除</text>
      </view>
      <view class="content">
        <view class="Good">
          <view
            v-if="goodDetail?.GoodsIcon.startsWith('icon')"
            class="circle"
            :class="goodDetail?.GoodsIcon"
          ></view>
          <view v-else class="circle bold">{{ goodDetail?.GoodsIcon }}</view>

          <view>{{ goodDetail?.Goods }}</view>
          <view class="userName">({{ goodDetail?.UserName }})</view>
          <view>
            {{ goodDetail.Amount }}
          </view>
        </view>
        <view class="zhichu">
          <text>账号</text>
          <text
            >{{ goodDetail?.AccountName }}/{{ goodDetail?.AccountTypeName }}/{{
              goodDetail?.AccountCard
            }}</text
          >
        </view>
        <view class="zhichu">
          <text>不计入预算</text>
          <checkbox-group class="isnotyusuan">
            <label>
              <checkbox :value="true" :checked="goodDetail?.IsNotYuSuan" />
            </label>
          </checkbox-group>
        </view>
        <view class="zhichu">
          <text>对方</text>
          <text>{{ goodDetail?.DuiFang }}</text>
        </view>
        <view class="zhichu">
          <text>来源</text>
          <text>{{ goodDetail?.Source }}</text>
        </view>
        <view class="zhichu">
          <text>时间</text>
          <text>{{ goodDetail?.DealTime }}</text>
        </view>
        <view class="zhichu">
          <text>备注</text>
          <text>{{ goodDetail?.Remark }}</text>
        </view>
      </view>
    </view>
  </uni-popup>
  <!-- 提示确认是否删除 弹窗 -->
  <uni-popup ref="alertDialog" type="dialog">
    <uni-popup-dialog
      type="warn"
      cancelText="取消"
      confirmText="确定"
      title="通知"
      content="确定要删除么？"
      @confirm="delGood"
      @close="cancel"
    ></uni-popup-dialog>
  </uni-popup>
  <!-- 提示确认是否注销 弹窗 -->
  <uni-popup ref="dropDialog" type="dialog">
    <uni-popup-dialog
      type="warn"
      cancelText="取消"
      confirmText="确定"
      title="通知"
      content="确定要注销么？注销后数据将清空！！！"
      @confirm="dropAccount"
      @close="cancelDrop"
    ></uni-popup-dialog>
  </uni-popup>
</template>

<script setup lang="ts">
import {
  DelGoodAPI,
  DropAccountAPI,
  GetAccountTypeNameAPI,
  GetDetailDataAPI,
  GetGoodDetailAPI,
  GetSameAccountAPI,
  GetUserSettingAPI,
  UpdateUserSettingAPI,
  type GetDetailDataParams,
} from '@/services/detail'
import { GetAccountAPI, GetAccountAmountAPI, UpdateAccountAPI } from '@/services/zichan'
import { useMemberStore } from '@/stores'
import type {
  AccountDetail,
  AccountTypeNameResponse,
  DataCount,
  GetSameAccountResponse,
  UserSetting,
} from '@/types/detail'
import type { GetAccountResponse } from '@/types/zichan'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
//默认值设置为FALSE，表示不加载
const ready = ref(false)
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// 获取会员信息
const memberStore = useMemberStore()
const yearData = ref<string[]>([
  '2024',
  '2025',
  '2026',
  '2027',
  '2028',
  '2029',
  '2030',
  '2031',
  '2032',
  '2033',
  '2034',
])
const curAccountTypeName = ref<GetSameAccountResponse>({
  AccountNo: '',
  AccountCard1AccountTypeName: '',
})
const selectYearIndex = ref<number>(0)
const curYear = ref<string>('ALL')
const monthData = ref<string[]>([
  '1',
  '2',
  '3',
  '4',
  '5',
  '6',
  '7',
  '8',
  '9',
  '10',
  '11',
  '12',
  'ALL',
])
const curMonth = ref<string>('ALL')
const selectMonthIndex = ref<number>(0)
const form = ref<GetDetailDataParams>({
  UserName: '',
  DealYear: 2024,
  DealMonth: 1,
  AccountNo: '',
  Auth: '',
  DealDay: 0,
  GoodsType: '',
  Goods: '',
  InOut: 0,
  TimeScope: '',
  OrderBy: 1,
  Require: '',
  UserGroup: '',
  LoginName: '',
})
const accountTypeNames = ref<GetSameAccountResponse[]>()
const pwd = ref('')
const amount = ref(0)
const AccountCard = ref('')
const AccountTypeName = ref('')
const iconPath = ref('')
const showMask = ref(true)
const userSetting = ref<UserSetting>()
const data = ref<DataCount[]>()
const getAccountResponse = ref<GetAccountResponse>()
const goodDetail = ref<AccountDetail>({
  ID: 0,
  AccountNo: '',
  UserName: '',
  DealTime: new Date(),
  DuiFang: '',
  Goods: '',
  InOut: 0,
  Amount: 0,
  Remark: '',
  GoodsType: '',
  Source: '',
  GoodsIcon: '',
  AccountName: '',
  AccountTypeName: '',
  AccountCard: '',
  IsNotYuSuan: false,
  IsAvg: false,
  IsRequire: false,
  IsNotMonthAccount: true,
})
const iconPathData = ref([
  { value: '../../static/images/pingan.png', text: '平安银行' },
  { value: '../../static/images/jianshe.png', text: '建设银行' },
  { value: '../../static/images/zhaoshang.png', text: '招商银行' },
  { value: '../../static/images/wechat.png', text: '微信' },
  { value: '../../static/images/zhifubao.png', text: '支付宝' },
  { value: '../../static/images/gongjijin.png', text: '公积金' },
  { value: '../../static/images/yanglao.png', text: '养老金' },
  { value: '../../static/images/gupiao.png', text: '股票' },
  { value: '../../static/images/xianjing.png', text: '现金' },
])
// uni-ui 弹出层组件
const popupDetail = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()
//计算属性
const maskedAmount = computed(() => {
  if (AccountCard?.value == '股票') {
    if (showMask.value) {
      const amountStr = getAccountResponse.value?.Amount.toString() || ''
      const maskedStr = '*'.repeat(amountStr.length)
      return maskedStr
    } else {
      return getAccountResponse.value?.Amount + '(' + getAccountResponse.value?.AmountSelf + ')'
    }
  } else if (!curAccountTypeName?.value?.AccountNo) {
    if (showMask.value) {
      const amountStr = amount.value.toString() || ''
      const maskedStr = '*'.repeat(amountStr.length)
      return maskedStr
    } else {
      return amount.value
    }
  } else {
    if (showMask.value) {
      const amountStr = getAccountResponse.value?.Amount.toString() || ''
      const maskedStr = '*'.repeat(amountStr.length)
      return maskedStr
    } else {
      return getAccountResponse.value?.Amount
    }
  }
})
const orderby = async () => {
  form.value.OrderBy = form.value.OrderBy == 1 ? 2 : 1
  await reFresh()
}
//修改商品
const OnUpdateGood = async (id: any) => {
  // await UpdateGoodAPI({
  //   ID: goodDetail.value!.ID,
  //   Auth: '07230602',
  //   AccountNo: goodDetail.value!.AccountNo,
  //   Amount: goodDetail.value!.Amount,
  //   IsNotYuSuan: goodDetail.value!.IsNotYuSuan,
  // })
  // popup.value?.close()
  // reFresh()
  uni.reLaunch({
    url:
      '/pages/NoteAcount/NoteAcount?pageType=update&id=' +
      id +
      '&backPage=/pages/card/cardDetail?accountNo=' +
      form.value.AccountNo,
  })
}
//添加商品
const add = async (id: any) => {
  // await UpdateGoodAPI({
  //   ID: goodDetail.value!.ID,
  //   Auth: '07230602',
  //   AccountNo: goodDetail.value!.AccountNo,
  //   Amount: goodDetail.value!.Amount,
  //   IsNotYuSuan: goodDetail.value!.IsNotYuSuan,
  // })
  // popup.value?.close()
  // reFresh()
  uni.reLaunch({
    url:
      '/pages/NoteAcount/NoteAcount?AccountNo=' +
      form.value.AccountNo +
      '&backPage=/pages/card/cardDetail?accountNo=' +
      encodeURIComponent(
        form.value.AccountNo +
          '&accountTypeName=' +
          curAccountTypeName.value.AccountCard1AccountTypeName +
          '&accountTypeNameAccountNo=' +
          curAccountTypeName.value.AccountNo,
      ),
  })
}
//选择账户类型
const pickerAccountTypeChange = async (e: any) => {
  const index = e.detail.value as number
  curAccountTypeName.value = accountTypeNames.value![index]
  if (curAccountTypeName.value.AccountNo) {
    form.value.AccountNo = curAccountTypeName.value.AccountNo //账户信息
    await initAccountInfo()
  } else {
    await InitAccountAmount(curAccountTypeName.value.AccountCard1AccountTypeName)
  }
  reFresh()
}
//加载初始化
onLoad(async () => {
  await InitUserSetting()
  showMask.value = true
  // 打印query参数
  console.log(route.query.id?.toString())
  form.value.AccountNo = route.query.accountNo!.toString()
  form.value.UserGroup = memberStore.profile!.UserGroup
  form.value.LoginName = memberStore.profile!.UserName
  //初始化年月
  const currentDate = new Date()
  form.value.DealYear = currentDate.getFullYear()
  form.value.DealMonth = currentDate.getMonth() + 1
  curYear.value = form.value.DealYear.toString()
  selectYearIndex.value = form.value.DealYear - 2024
  curMonth.value = form.value.DealMonth.toString()
  selectMonthIndex.value = form.value.DealMonth - 1
  //账户信息
  await initAccountInfo()
  //用户
  form.value.Auth = memberStore.profile!.Token
  form.value.UserName = getAccountResponse.value!.UserName
  await InitAccountTypeName()
  if (route.query.accountTypeName) {
    curAccountTypeName.value.AccountCard1AccountTypeName = route.query.accountTypeName!.toString()
    curAccountTypeName.value.AccountNo = route.query.accountTypeNameAccountNo!.toString()
    await InitAccountAmount(curAccountTypeName.value.AccountCard1AccountTypeName)
  } else {
    curAccountTypeName.value.AccountCard1AccountTypeName = AccountCard.value
    curAccountTypeName.value.AccountNo = form.value.AccountNo
  }

  reFresh()
  ready.value = true
})
//初始化账户类型列表
const InitAccountTypeName = async () => {
  if (memberStore.profile) {
    const res = await GetSameAccountAPI({
      Auth: memberStore.profile.Token,
      AccountNo: form.value.AccountNo,
    })
    accountTypeNames.value = res.result
  }
}
//初始化账户信息
const initAccountInfo = async () => {
  const res = await GetAccountAPI({
    AccountNo: form.value.AccountNo,
    Auth: memberStore.profile!.Token,
  })
  getAccountResponse.value = res.result
  amount.value = getAccountResponse.value.Amount
  AccountCard.value = getAccountResponse.value.AccountCard
  AccountTypeName.value = getAccountResponse.value.AccountTypeName
  iconPath.value = getAccountResponse.value.iconPath
}
//初始化账户信息
const InitAccountAmount = async (AccountCard1AccountTypeName: string) => {
  const res = await GetAccountAmountAPI({
    Auth: memberStore.profile!.Token,
    UserName: form.value.UserName,
    AccountCard1AccountTypeName: AccountCard1AccountTypeName,
  })
  amount.value = res.result.Amount
}

//刷新事件
const reFresh = async () => {
  if (memberStore.profile) {
    const res = await GetDetailDataAPI({
      UserName: '',
      DealYear: form.value.DealYear,
      DealMonth: form.value.DealMonth,
      DealDay: form.value.DealDay,
      AccountNo: curAccountTypeName.value.AccountNo,
      Auth: form.value.Auth,
      GoodsType: form.value.GoodsType,
      Goods: form.value.Goods,
      InOut: form.value.InOut,
      TimeScope: form.value.TimeScope,
      OrderBy: form.value.OrderBy,
      Require: form.value.Require,
      UserGroup: form.value.UserGroup,
      LoginName: '',
    })
    data.value = res.result
    uni.showToast({ icon: 'success', title: '刷新成功' })
  } else {
    uni.showToast({ icon: 'none', title: '请先登录' })
    setTimeout(() => {
      // 页面跳转
      uni.switchTab({ url: '/pages/my/my' })
    }, 500)
  }
}
//日期改变
const bindDateChange = (e: any) => {
  const [year, month] = e.detail.value.split('-')
  form.value.DealYear = year
  form.value.DealMonth = month
  reFresh()
}
const pickerYearChange = (e: any) => {
  const index = e.detail.value as number
  curYear.value = yearData.value![index]
  if (curYear.value != 'ALL') {
    form.value.DealYear = Number(curYear.value)
  } else {
    form.value.DealYear = 0
  }
  reFresh()
}
const pickerMonthChange = (e: any) => {
  const index = e.detail.value as number
  curMonth.value = monthData.value![index]
  if (curMonth.value != 'ALL') {
    form.value.DealMonth = Number(curMonth.value)
  } else {
    form.value.DealMonth = 0
  }
  reFresh()
}

//返回
const Onleft = () => {
  uni.switchTab({ url: '/pages/card/card' })
}
//金额隐藏事件
const toggleMask = () => {
  showMask.value = !showMask.value
}
//初始化用户配置
const InitUserSetting = async () => {
  if (memberStore.profile) {
    const res = await GetUserSettingAPI({ UserName: memberStore.profile.UserName })
    userSetting.value = res.result
  }
}
//修改用户配置
const UpdateUserSetting = async () => {
  if (memberStore.profile) {
    await UpdateUserSettingAPI(userSetting.value!)
  }
}
//===编辑弹窗===
const searchDialog = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()
//打开
const OpenSarchDialog = async () => {
  if (!curAccountTypeName?.value?.AccountNo) {
    uni.showToast({
      icon: 'error',
      title: '请选择具体账户！' + curAccountTypeName.value.AccountCard1AccountTypeName + '无法编辑',
    })
  } else {
    searchDialog.value?.open()
  }
}
//确认
const SubmitSarchDialog = async () => {
  if (memberStore.profile) {
    await UpdateAccountAPI({
      Auth: memberStore.profile.Token,
      AccountNo: form.value.AccountNo,
      Amount: amount.value,
      UserName: memberStore.profile.UserName,
      AccountCard: AccountCard.value,
      AccountTypeName: AccountTypeName.value,
      iconPath: iconPath.value,
      UserGroup: memberStore.profile.UserGroup,
    })
    await initAccountInfo()
    await reFresh()
    CloseSarchDialog()
  }
}
//取消
const CloseSarchDialog = async () => {
  searchDialog.value?.close()
}
//弹出层
// uni-ui 弹出层组件
//打开
const OpenPwdDialog = async () => {
  if (memberStore.profile && showMask.value) {
    // pwd.value = ''
    // popup.value?.open()
    //取消弹窗输入密码方式，对账时、已刷新就需要输入密码才能查看，繁琐
    showMask.value = false
  } else {
    showMask.value = true
  }
}
const popup = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()
const ComfirmPwd = async () => {
  if (memberStore.profile && showMask.value) {
    if (pwd.value == memberStore.profile.Token) {
      pwd.value = ''
      showMask.value = false
      popup.value?.close()
      setTimeout(() => {
        showMask.value = true
      }, 1000 * 30)
    } else {
      uni.showToast({ icon: 'error', title: '密码错误' })
    }
  }
}
//打开明细
const openPopup = async (id: number) => {
  popupDetail.value?.open()
  const res = await GetGoodDetailAPI({ ID: id })
  goodDetail.value = res.result
}
//提示框
const alertDialog = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()
const OnAlertDialog = async () => {
  alertDialog.value?.open()
}
//注销框
const dropDialog = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()
const OnDropDialog = async () => {
  dropDialog.value?.open()
}
//修改商品
const OnUpdateGoodDetail = async () => {
  // await UpdateGoodAPI({
  //   ID: goodDetail.value!.ID,
  //   Auth: '07230602',
  //   AccountNo: goodDetail.value!.AccountNo,
  //   Amount: goodDetail.value!.Amount,
  //   IsNotYuSuan: goodDetail.value!.IsNotYuSuan,
  // })
  // popup.value?.close()
  // reFresh()
  uni.reLaunch({
    url:
      '/pages/NoteAcount/NoteAcount?pageType=update&id=' +
      goodDetail.value!.ID +
      '&backPage=/pages/card/cardDetail?accountNo=' +
      encodeURIComponent(
        form.value.AccountNo +
          '&accountTypeName=' +
          curAccountTypeName.value.AccountCard1AccountTypeName +
          '&accountTypeNameAccountNo=' +
          curAccountTypeName.value.AccountNo,
      ),
  })
}
//取消
const cancel = async () => {
  alertDialog.value?.close()
}
//注销
const cancelDrop = async () => {
  dropDialog.value?.close()
}
//确认删除
const delGood = async () => {
  await DelGoodAPI({
    ID: goodDetail.value!.ID,
    Auth: memberStore.profile!.Token,
  })
  alertDialog.value?.close()
  popupDetail.value?.close()
  reFresh()
}
//确认删除
const dropAccount = async () => {
  await DropAccountAPI({
    Auth: memberStore.profile!.Token,
    AccountNo: form.value.AccountNo,
  })
  dropDialog.value?.close()
  Onleft()
}
</script>

<style lang="scss">
@import './styles/cardDetail.scss';
</style>
